<template>
  <div class="container">
    <div class="search">
      <a-input v-model="searchKey" placeholder="搜索名称/编码" allow-clear>
        <template #prefix><icon-search /></template>
      </a-input>
      <a-button v-permission="['system:apiCategory:add']" type="primary" @click="onAdd">
        <template #icon><icon-plus /></template>
      </a-button>
    </div>
    <div class="tree-wrapper">
      <div class="tree">
        <a-tree
          ref="treeRef"
          :data="treeData"
          show-line
          block-node
          default-expand-all
          :selected-keys="selectedKeys"
          @select="select"
        >
          <template #switcher-icon="node, { isLeaf }">
            <IconCaretDown v-if="!isLeaf" />
            <IconIdcard v-else />
          </template>
          <template #title="node">
            <a-typography-paragraph
              :ellipsis="{
                rows: 1,
                showTooltip: true,
                css: true,
              }"
            >
              {{ node?.title }}
            </a-typography-paragraph>
          </template>
          <template #extra="node">
            <a-trigger trigger="click" align-point animation-name="slide-dynamic-origin" auto-fit-transform-origin position="bl" scroll-to-close>
              <icon-more v-if="has.hasPermOr(['system:apiCategory:update', 'system:apiCategory:delete'])" class="action" />
              <template #content>
                <RightMenu :data="node" @on-menu-item-click="onMenuItemClick" />
              </template>
            </a-trigger>
          </template>
        </a-tree>
      </div>
    </div>
    <CategoryAddModel ref="CateAddModelRef" :categorys="categoryList" @save-success="getCategoryTree" />
  </div>
</template>

<script setup lang="tsx">
import { Message, Modal } from '@arco-design/web-vue'
import type { TreeInstance, TreeNodeData } from '@arco-design/web-vue'
import { ref } from 'vue'
import CategoryAddModel from './CategoryAddModel.vue'
import RightMenu from './RightMenu.vue'
import { useApiCategory } from '@/hooks/app/useApiCategory'
import { deleteApiCategory, exportApi } from '@/apis/system/api'
import has from '@/utils/has'
import { useDownload } from '@/hooks'

const emit = defineEmits<{
  (e: 'node-click', keys: Array<any>): void
}>()

// 选中节点
const selectedKeys = ref()
const select = (keys: Array<any>) => {
  if (selectedKeys.value && selectedKeys.value[0] === keys[0]) {
    return
  }
  selectedKeys.value = keys
  emit('node-click', keys)
}

const treeRef = ref<TreeInstance>()
// 查询树列表
const { categoryList, getCategoryTree } = useApiCategory({
  onSuccess: () => {
    nextTick(() => {
      treeRef.value?.expandAll(true)
      select([categoryList.value[0]?.key])
    })
  },
})

// 过滤树
const searchKey = ref('')
const search = (keyword: string) => {
  const loop = (data: TreeNodeData[]) => {
    const result = [] as TreeNodeData[]
    data.forEach((item: TreeNodeData) => {
      if (item.title?.toLowerCase().includes(keyword)) {
        result.push({ ...item })
      } else if (item.children) {
        const filterData = loop(item.children)
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData,
          })
        }
      }
    })
    return result
  }
  return loop(categoryList.value)
}

const treeData = computed(() => {
  if (!searchKey.value) return categoryList.value
  return search(searchKey.value.toLowerCase())
})
const CateAddModelRef = ref<InstanceType<typeof CategoryAddModel>>()
const onAdd = () => {
  CateAddModelRef.value?.onAdd()
}
function getNodeAndChildrenKeys(node: TreeNodeData): (string | number)[] {
  const keys: (string | number)[] = []

  if (node.key !== undefined) {
    keys.push(node.key)
  }

  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      keys.push(...getNodeAndChildrenKeys(child))
    }
  }

  return keys
}
// 点击菜单项
const onMenuItemClick = (mode: string, node: TreeNodeData) => {
  if (mode === 'update') {
    CateAddModelRef.value?.onUpdate(node)
  } else if (mode === 'export') {
    useDownload(() => exportApi({ ids: getNodeAndChildrenKeys(node) }))
  } else if (mode === 'delete') {
    Modal.warning({
      title: '提示',
      content: `是否确定删除接口分类「${node.title}」？`,
      hideCancel: false,
      okButtonProps: { status: 'danger' },
      onBeforeOk: async () => {
        try {
          const res = await deleteApiCategory([node.key])
          if (res.success) {
            Message.success('删除成功')
            await getCategoryTree()
          }
          return res.success
        } catch (error) {
          return false
        }
      },
    })
  }
}

onMounted(() => {
  getCategoryTree()
})
</script>

<style scoped lang="scss">
:deep(.arco-tree-node-title-text) {
  width: 100%;
  white-space: nowrap;
}

:deep(.arco-tree-node) {
  line-height: normal;
  border-radius: var(--border-radius-medium);
  margin: 5px 0;
  .action {
    opacity: 0;
    margin-right: 8px;
    padding: 4px;
    transition: all 0.25s;
    border-radius: 8px;

    &:hover{
      background-color: var(--color-bg-1);
    }
  }
  &:hover {
    background-color: var(--color-secondary-hover);
    .action {
      opacity: 1;
    }
  }
}

:deep(.arco-tree-node-selected) {
  font-weight: bold;
  background-color: rgba(var(--primary-6), 0.1);
  &:hover {
    background-color: rgba(var(--primary-6), 0.1);
  }
  .arco-typography {
    color: rgb(var(--primary-6));
  }
}

.container {
  flex: 1;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  height: 100%;

  .search {
    display: flex;
    justify-content: start;
    margin-bottom: 10px;
    .arco-btn {
      margin-left: 8px;
      padding: 0 15px;
    }
  }

  .tree-wrapper {
    flex: 1;
    overflow: hidden;
    background-color: var(--color-bg-1);
    position: relative;
    height: 100%;
/*    margin-bottom:10px;*/
    .tree {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      overflow: auto
    }
  }
}
</style>
